import Mock from 'mockjs'
import { cloneDeep } from 'lodash'

// 初始化数据存储
const initStorage = () => {
  if (!localStorage.getItem('mock_orders')) {
    const orders = Mock.mock({
      'list|30': [{
        'id|+1': 1000,
        'orderNo': '@string("number", 10)',
        'userId': 1,
        'status|1': ['pending', 'paid', 'processing', 'completed', 'canceled'],
        'totalPrice|100-5000': 1,
        'paymentMethod': () => Mock.Random.pick(['alipay', 'wechat', 'balance']),
        'createdAt': '@datetime',
        'updatedAt': '@datetime',
        'items|1-5': [{
          'productId|+1': 100,
          'name': '@ctitle(6,12)',
          'quantity|1-3': 1,
          'price|80-500': 1,
          'thumb': Mock.Random.image('100x100', '#4A7BF7', 'product')
        }],
        'address': {
          'contact': '@cname',
          'mobile': /^1[3-9]\d{9}/,
          'address': '@county(true)'
        }
      }]
    }).list
    localStorage.setItem('mock_orders', JSON.stringify(orders))
  }
}
initStorage()

// 数据操作方法
const getOrders = () => JSON.parse(localStorage.getItem('mock_orders')) || []
const saveOrders = (data) => localStorage.setItem('mock_orders', JSON.stringify(data))

// 获取产品库存（需与产品接口同步）
const getProductStock = (productId) => {
  const products = JSON.parse(localStorage.getItem('mock_products')) || []
  return products.find(p => p.id === productId)?.stock || 0
}

// 获取订单列表接口
Mock.mock(/\/api\/orders(?:\?.*)?/, 'get', (req) => {
  const query = new URLSearchParams(req.url.split('?')[1])
  const params = {
    page: parseInt(query.get('page')) || 1,
    pageSize: parseInt(query.get('pageSize')) || 10,
    status: query.get('status'),
    userId: parseInt(query.get('userId'))
  }

  let orders = getOrders()

  // 过滤条件
  if (params.userId) orders = orders.filter(o => o.userId === params.userId)
  if (params.status) orders = orders.filter(o => o.status === params.status)

  // 分页处理
  const start = (params.page - 1) * params.pageSize
  return {
    code: 200,
    data: {
      list: cloneDeep(orders.slice(start, start + params.pageSize)),
      pagination: {
        total: orders.length,
        currentPage: params.page,
        pageSize: params.pageSize,
        totalPages: Math.ceil(orders.length / params.pageSize)
      }
    }
  }
})

// 创建订单接口
Mock.mock('/api/orders', 'post', (req) => {
  const { items, address } = JSON.parse(req.body)
  
  // 验证库存
  const stockCheck = items.every(item => {
    return getProductStock(item.productId) >= item.quantity
  })
  
  if (!stockCheck) {
    return { code: 4001, message: '部分商品库存不足' }
  }

  // 生成订单
  const newOrder = {
    id: getOrders().length + 1000,
    orderNo: Date.now().toString().slice(-10),
    userId: 1,
    status: 'pending',
    totalPrice: items.reduce((sum, item) => sum + item.price * item.quantity, 0),
    items: cloneDeep(items),
    address,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString()
  }

  // 扣减库存
  const products = JSON.parse(localStorage.getItem('mock_products'))
  items.forEach(item => {
    const product = products.find(p => p.id === item.productId)
    if (product) product.stock -= item.quantity
  })
  localStorage.setItem('mock_products', JSON.stringify(products))

  // 保存订单
  const orders = getOrders()
  orders.unshift(newOrder)
  saveOrders(orders)

  return { code: 200, data: newOrder }
})

// 获取订单详情接口
Mock.mock(/\/api\/orders\/\d+/, 'get', (req) => {
  const orderId = req.url.match(/\/api\/orders\/(\d+)/)[1]
  const order = getOrders().find(o => o.id == orderId)
  return order 
    ? { code: 200, data: order }
    : { code: 404, message: '订单不存在' }
})

// 取消接口
Mock.mock(/\/api\/orders\/\d+\/cancel/, 'put', (req) => {
  const orderId = req.url.match(/\/api\/orders\/(\d+)\/cancel/)[1]
  const orders = getOrders()
  const order = orders.find(o => o.id == orderId)
  
  if (!order) return { code: 404, message: '订单不存在' }
  if (!['pending', 'paid'].includes(order.status)) {
    return { code: 4002, message: '当前状态不可取消' }
  }

  // 恢复库存
  const products = JSON.parse(localStorage.getItem('mock_products'))
  order.items.forEach(item => {
    const product = products.find(p => p.id === item.productId)
    if (product) product.stock += item.quantity
  })
  localStorage.setItem('mock_products', JSON.stringify(products))

  // 更新状态
  order.status = 'canceled'
  order.updatedAt = new Date().toISOString()
  saveOrders(orders)

  return { code: 200, data: order }
})

// 支付接口
Mock.mock(/\/api\/orders\/\d+\/payment/, 'post', (req) => {
  const orderId = req.url.match(/\/api\/orders\/(\d+)\/payment/)[1]
  const { paymentMethod } = JSON.parse(req.body)
  const orders = getOrders()
  const order = orders.find(o => o.id == orderId)

  if (!order) return { code: 404, message: '订单不存在' }
  if (order.status !== 'pending') {
    return { code: 4003, message: '订单状态不可支付' }
  }

  // 模拟支付结果
  order.status = 'paid'
  order.paymentMethod = paymentMethod
  order.updatedAt = new Date().toISOString()
  saveOrders(orders)

  return { code: 200, data: { ...order, paymentTime: new Date().toISOString() } }
})